<?php

namespace addons\shopro\controller;

use app\admin\model\shopro\Withdraw as WithdrawModel;
use addons\shopro\service\Withdraw as WithdrawLibrary;
use think\Db;
class Withdraw extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index() 
    {
        $user = auth_user();
        $withdraws = WithdrawModel::where(['user_id' => $user->id])->order('id desc')->paginate($this->request->param('list_rows', 10))->each(function ($withdraw) {
            $withdraw->hidden(['withdraw_info']);
            $withdraw->remarks=Db::name("shopro_withdraw_log")->where(["withdraw_id"=>$withdraw->id,"oper_type"=>"system"])->value("content");
        });

        $this->success('获取成功', $withdraws);
    }


    // 提现规则
    public function rules()
    {
        $user = auth_user();
        $config = (new WithdrawLibrary($user))->config;

        $this->success('提现规则', $config);
    }


    // 发起提现请求
    public function apply()
    {
        $user = auth_user();
        $params = $this->request->param();

        $this->svalidate($params, ".apply");
        if (!empty($user["agent"])&& $user["agent"]["level"] >2) {
            $commission_rules=$user["agent"]["level_info"]["commission_rules"];
            if(empty($commission_rules)) $this->error('请检查会员等级');
            /*$pay_money=bcsub($user["money"],$params["money"],2);
            $pay_money=bcdiv($pay_money,($commission_rules["commission_1"]/100),2);
            $pay_money=bcsub($user["payment_goods"],$pay_money,2);
            if($pay_money<=0) $this->error('余额不足');*/
            $pay_money=bcsub($user["money"],$params["money"],2);
            $pay_money=bcdiv($pay_money,($commission_rules["commission_1"]/100),2);
            $pay_money=bcsub($pay_money,$user["payment_goods"],2);
            if($pay_money<=0) $this->error('余额不足');
        }
        $withdrawLib = new WithdrawLibrary($user);
        $withdraw = $withdrawLib->apply($params);

        $this->success('申请成功', $withdraw);
    }
}
